package br.com.pnfp.web.test;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ImportarDoador {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		new ImportarDoador().start();
	}

	public void start() throws Exception {
		
		List<String[]> list = new ArrayList<String[]>();
		
		Scanner originalFile = new Scanner(new FileInputStream("/home/andrew/Pelegrino/cnpjDoador.csv"), "ISO-8859-1");
		int i=0;
		while(originalFile.hasNextLine()) {
			String line = originalFile.nextLine();
			String[] value = line.split(";\\s*");
			
			String cnpj = value[0].trim();
			if(ValidaCNPJ.isCNPJ(cnpj)) {
				list.add(value);
			}
			i++;
		}
		System.out.println("**********************");
		System.out.println("Total de Registros: " + i);
		System.out.println("CNPJ Válidos: " + list.size());
		printSql(list);
		
	}
	
	private void printSql(List<String[]> list) throws Exception {
		
		int codigoRamoAtividade = 4;
		int codigoUsuario = 1;
		int codigoLocalidade = 2;
		String razaoSocialPadrao = "Sem Razao Social";
		
		FileWriter writer = new FileWriter("/home/andrew/Pelegrino/cargaDoador.sql");
		FileWriter csvFile = new FileWriter("/home/andrew/Pelegrino/novoArquivo.csv");
		
		int totalSemRazaoSocial= 0;
		
		for(String[] value : list) {
			
			StringBuilder sql = new StringBuilder();
			sql.append("INSERT INTO tb_doador(dc_cnpj, dc_razao_social, cd_ramo_atividade, cd_localidade, cd_usuario_cadastro, dt_cadastro) ");
			String razaoSocial = value[1];
			if(value[1].trim().equals("#N/D")) {
				razaoSocial = razaoSocialPadrao;
				totalSemRazaoSocial++;
			}
			sql.append("values('").append(value[0]).append("', '").append(razaoSocial.toUpperCase()).append("',").append(codigoRamoAtividade).append(",").append(codigoLocalidade).append(",").append(codigoUsuario).append(",now());");
			System.out.println(sql.toString());
			writer.write(sql.toString() + "\n");
			
			
			StringBuilder csv = new StringBuilder();
			csv.append(value[0]).append(";").append(razaoSocial).append("\n");
			csvFile.write(csv.toString());
			
		}
		System.out.println("Sem Razao Social: " + totalSemRazaoSocial);		
	}
}
